import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import WallateGet from "./component/index.js";
import Navbar from "./component/Navbar.js";
// import Upload from "./component/Upload.js";
import Upload from "./component/Upload.js";
import PetList from "./component/PetList.js";
import ReCharge from "./component/ReCharge.js";
import MyPet from "./component/MyPet.js";
import { PetDetail } from "./component/PetDetail.js";
import React, { useEffect, useState } from "react";

// import { useState } from "react";
function App() {
  useEffect(() => {
    document.title = "pet Mark";
  });
  const [walletAddress, setWallet] = useState("");

  useEffect(() => {
    addWalletListener();
  }, []);

  function addWalletListener() {
    try {
      if (window.ethereum) {
        window.ethereum.on("accountsChanged", (accounts) => {
          if (accounts.length > 0) {
            setWallet(accounts[0]);
          } else {
            setWallet("");
          }
        });
      }
    } catch (e) {
      alert("get Wallate error");
    }
  }

  async function getWalletAddress() {
    if (window.ethereum) {
      try {
        const accounts = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        setWallet(accounts[0]); // Set the first account as the connected account
      } catch (error) {
        // console.error("Error connecting to wallet:", error);
        alert("get Wallate error");
      }
    }
  }

  return (
    <div id="container">
      <Router>
        <Navbar onConnectWallate={getWalletAddress()} address={walletAddress} />
        <Routes>
          <Route
            path="/create-nft"
            element={<Upload address={walletAddress} />}
          />
          <Route path="/" element={<PetList />} />
          <Route
            path="/charge"
            element={<ReCharge address={walletAddress} />}
          />
          <Route path="/my-pet" element={<MyPet address={walletAddress} />} />
          <Route path="/nft-detail/:tokenId" element={<PetDetail />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;
